package com.spark.quartz.utils;

import com.spark.common.utils.SpringUtils;
import com.spark.quartz.entity.QrtzJob;
import com.spark.quartz.entity.QrtzJobLog;
import com.spark.quartz.mapper.QrtzJobLogMapper;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * 定时任务执行器
 *
 * @author LYCHEE
 * @date 2025/4/3 10:26
 */
public class QuartzJobExecute extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        QrtzJob job = (QrtzJob) context.getMergedJobDataMap().get("JOB_DATA");
        QrtzJobLog log = new QrtzJobLog();
        log.setJobId(job.getId());
        log.setInvokeTarget(job.getInvokeTarget());
        log.setCreateTime(new Date());
        try {
            // 执行任务
            if (job.getConcurrent() == 1) {
                // 禁止并发，添加同步锁
                synchronized (this) {
                    JobInvokeUtil.invokeMethod(job.getInvokeTarget());
                }
            } else {
                JobInvokeUtil.invokeMethod(job.getInvokeTarget());
            }
            log.setStatus(0);
            log.setJobMessage("任务执行成功");
        } catch (Exception e) {
            log.setStatus(1);
            log.setExceptionInfo(ExceptionUtils.getStackTrace(e));
            log.setJobMessage("任务执行失败");
            throw new JobExecutionException(e);
        } finally {
            // 保存日志到数据库
            SpringUtils.getBean(QrtzJobLogMapper.class).insert(log);
        }
    }
}
